package com.exm.controller;

import com.exm.pojo.DataLog;
import com.exm.service.DataService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
public class LoginController {

    // 显示登录页面
    @GetMapping("/login")
    public String showLoginPage() {
        return "login";  // 返回 login.html
    }

    @Autowired
    DataService dataService;

    // 处理登录请求
    @PostMapping("/login")
    public String login(@RequestParam String username, @RequestParam String password, Model model) throws JsonProcessingException {
        // 检查用户名和密码
        if ("admin".equals(username) && "123456".equals(password)) {
            List<DataLog> data = dataService.getData();
            ObjectMapper objectMapper = new ObjectMapper();
            String jsonDataLogs = objectMapper.writeValueAsString(data); // 将 dataLogs 转换为 JSON 字符串
            model.addAttribute("dataLogs", jsonDataLogs);
            // 登录成功，跳转到控制台页面
            return "dashboard";
        } else {
            // 登录失败，返回错误信息
            model.addAttribute("error", "Invalid credentials");
            return "login";  // 返回到 login.html 页面
        }
    }
}
